package com.java.simple.study.juc.p7;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhoujunlin
 * @date 2022年08月07日 22:10
 * @desc
 */
@Slf4j(topic = "c.TestExecutors")
public class TestExecutors {

    public static void main(String[] args) {
        // test1();
        test2();
    }

    private static void test2() {
        /**
         * 只有一个线程 任务多的话会放入无界队列排队
         * 某个任务报错  不会影响其他任务
         */
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        singleThreadExecutor.execute(() -> {
            log.debug("1");
            int i = 1 / 0;
        });
        singleThreadExecutor.execute(() -> {
            log.debug("2");
        });
        singleThreadExecutor.execute(() -> {
            log.debug("3");
        });
    }


    private static void test1() {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2, new ThreadFactory() {
            private AtomicInteger tNo = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "mypool_t" + tNo.getAndIncrement());
            }
        });

        /**
         * 观察线程名  会有一个线程被复用了
         */
        fixedThreadPool.execute(() -> {
            log.debug("1");
        });

        fixedThreadPool.execute(() -> {
            log.debug("2");
        });

        fixedThreadPool.execute(() -> {
            log.debug("3");
        });
    }

}
